package com.ywu.application.standard.tenant.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.ywu.application.standard.adminUser.entity.UserEntity;
import com.ywu.application.standard.adminUser.service.UserService;
import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.common.entity.PageList;
import com.ywu.common.mapper.YwuBeanMapper;
import com.ywu.common.page.PageService;
import com.ywu.common.result.CommonResult;
import com.ywu.application.standard.tenant.constant.TenantConstant;
import com.ywu.application.standard.tenant.data.TenantRepository;
import com.ywu.application.standard.tenant.dto.TenantDto;
import com.ywu.application.standard.tenant.dto.TenantUserDTO;
import com.ywu.application.standard.tenant.entity.TenantEntity;
import com.ywu.application.standard.tenant.entity.TenantUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName TenantService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/5/3 14:45
 * @Version 1.0
 **/
@Service
public class TenantService {
    @Autowired
    private TenantRepository tenantRepository;

    @Autowired
    private UserService userService;

    /**
    * @Author GroundDemo
    * @Description 添加租户信息
    * @Date 17:14 2024/5/3
    * @Param [tenantDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> addTenantInfo(TenantDto tenantDto) {
        TenantDto tenantIdSearch = new TenantDto();
        tenantIdSearch.setTenantId(tenantDto.getTenantId());
        // 判断租户ID是否存在
        List<TenantEntity> tenantEntities = tenantRepository.queryTenantInfo(tenantIdSearch);
        if (!CollectionUtils.isEmpty(tenantEntities)) {
            return CommonResult.error().setErrorCode(TenantConstant.TENANT_ID_HAS_EXIST)
                    .setMessage(TenantConstant.TENANT_ID_HAS_EXIST);
        }
        // 构建entity对象
        TenantEntity tenantEntity = YwuBeanMapper.map(tenantDto, TenantEntity.class);
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        tenantEntity.createInfo(currentContext.getYwuContextUser().getUserAccount());
        tenantRepository.addTenantInfo(tenantEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 更新租户信息
    * @Date 17:16 2024/5/3
    * @Param [tenantDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateTenantInfo(TenantDto tenantDto) {
        // 校验ID是否存在
        TenantDto tenantIdSearch = new TenantDto();
        tenantIdSearch.setId(tenantDto.getId());
        // 判断租户ID是否存在
        List<TenantEntity> tenantEntities = tenantRepository.queryTenantInfo(tenantIdSearch);
        if (CollectionUtils.isEmpty(tenantEntities)) {
            return CommonResult.error().setErrorCode(TenantConstant.TENANT_INFO_ID_IS_NOT_EXIST)
                    .setMessage(TenantConstant.TENANT_INFO_ID_IS_NOT_EXIST);
        }
        TenantEntity tenantEntity = YwuBeanMapper.map(tenantDto, TenantEntity.class);
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        tenantEntity.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        tenantRepository.updateTenantInfo(tenantEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除租户信息
    * @Date 17:17 2024/5/3
    * @Param [tenantDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> deleteTenantInfo(TenantDto tenantDto) {
        tenantRepository.deleteTenantInfo(tenantDto);
        // 删除租户是删除与用户是授权关系
        tenantRepository.deleteTenantUserPermissionByTenantId(tenantDto);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询租户信息列表
    * @Date 17:18 2024/5/3
    * @Param [tenantDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryTenantInfo(TenantDto tenantDto) {
        // 查询数量
        int record = tenantRepository.queryTenantInfoCount(tenantDto);
        PageService.execPageStartAndEnd(tenantDto.getPageInfo());
        List<TenantEntity> tenantEntities = tenantRepository.queryTenantInfoList(tenantDto);
        // 关联查询租户管理员信息
        List<Integer> userIds = tenantEntities.stream().map(TenantEntity::getTenantAdminUserId).collect(Collectors.toList());
        CommonResult<List<UserEntity>> userRes = userService.queryUserByUserIdBatch(userIds);
        List<UserEntity> userEntities = userRes.getData();
        if (CollectionUtils.isNotEmpty(userEntities)) {
            Map<Integer, UserEntity> userEntityMap = userEntities.stream().collect(Collectors.toMap(UserEntity::getId, res -> res, (v1, v2) -> v1));
            // 填充用户账号
            for (TenantEntity entity : tenantEntities) {
                if (userEntityMap.containsKey(entity.getTenantAdminUserId())) {
                    entity.setTenantUserInfo(userEntityMap.get(entity.getTenantAdminUserId()));
                }
            }
        }
        PageList<TenantEntity> tenantEntityPageList = new PageList<>(tenantDto.getPageInfo().getPageIndex(),
                tenantDto.getPageInfo().getPageSize(), record, tenantEntities);
        return CommonResult.success(tenantEntityPageList);
    }

    /**
    * @Author GroundDemo
    * @Description  租户授权
    * @Date 22:27 2024/5/23
    * @Param [tenantUserDTO]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> tenantUserAuthorize(TenantUserDTO tenantUserDTO) {
        // 判断当前userId和租户ID的关系是否已经存在
        TenantUserEntity tenantUserEntity = tenantRepository.queryTenantUserByUserIdAndTenant(tenantUserDTO.getUserId(), tenantUserDTO.getTenantId());
        if (Objects.nonNull(tenantUserEntity)) {
            return CommonResult.error().setErrorCode("user.has.been.authorized.tenant")
                    .setMessage("用户已被授权租户");
        }
        // 插入授权记录
        TenantUserEntity tenantUser = YwuBeanMapper.map(tenantUserDTO, TenantUserEntity.class);
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        tenantUser.createInfo(currentContext.getYwuContextUser().getUserAccount());
        tenantRepository.insertTenantUserInfo(tenantUser);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询租户授权信息
    * @Date 22:44 2024/5/23
    * @Param [tenantUserDTO]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> tenantUserAuthorizeInfoQuery(TenantUserDTO tenantUserDTO) {
        // 分页查询，先查询数量
        int record = tenantRepository.queryTenantUserInfoCount(tenantUserDTO);
        // 查询分页
        PageService.execPageStartAndEnd(tenantUserDTO.getPageInfo());
        List<TenantUserDTO> tenantUserDTOList = tenantRepository.queryTenantUserInfo(tenantUserDTO);
        if (CollectionUtils.isEmpty(tenantUserDTOList)) {
            PageList<TenantUserDTO> tenantUserDTOPageList = new PageList<>(tenantUserDTO.getPageInfo().getPageIndex(),
                    tenantUserDTO.getPageInfo().getPageSize(), 0, tenantUserDTOList);
            return CommonResult.success(tenantUserDTOPageList);
        }
        // 根据userId查询用户信息
        List<Integer> userIds = tenantUserDTOList.stream().map(TenantUserDTO::getUserId).collect(Collectors.toList());
        CommonResult<List<UserEntity>> queryRes = userService.queryUserByUserIdBatch(userIds);
        if (!StringUtils.equals(queryRes.getCode(), "200")) {
            return CommonResult.error().setErrorCode("query user info error");
        }
        List<UserEntity> data = queryRes.getData();
        Map<Integer, UserEntity> userEntityMap = data.stream().collect(Collectors.toMap(UserEntity::getId, res -> res, (v1, v2) -> v1));
        // 拼接对象
        for (TenantUserDTO userDTO : tenantUserDTOList) {
            if (userEntityMap.containsKey(userDTO.getUserId())) {
                UserEntity userEntity = userEntityMap.get(userDTO.getUserId());
                userDTO.setUserAccount(userEntity.getUserAccount());
                userDTO.setUserNickName(userEntity.getUserNickName());
            }
        }
        // 构建分页对象
        PageList<TenantUserDTO> tenantUserDTOPageList = new PageList<>(tenantUserDTO.getPageInfo().getPageIndex(),
                tenantUserDTO.getPageInfo().getPageSize(), record, tenantUserDTOList);
        return CommonResult.success(tenantUserDTOPageList);
    }

    /**
    * @Author GroundDemo
    * @Description 删除租户授权
    * @Date 10:13 2024/5/25
    * @Param [tenantUserDTO]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> tenantUserAuthDelete(TenantUserDTO tenantUserDTO) {
        TenantUserEntity tenantUserEntity = YwuBeanMapper.map(tenantUserDTO, TenantUserEntity.class);
        tenantRepository.deleteTenantUserInfo(tenantUserEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 根据用户ID查询该用户下的所有租户
    * @Date 21:40 2024/5/30
    * @Param [tenantUserDTO]
    * @return com.ywu.common.result.CommonResult<java.util.List<com.ywu.tenant.standard.entity.TenantEntity>>
    **/
    public CommonResult<List<TenantEntity>> queryTenantInfoByUserId(TenantUserDTO tenantUserDTO) {
        List<TenantEntity> tenantEntities = tenantRepository.queryTenantInfoByUserId(tenantUserDTO.getUserId());
        return CommonResult.success(tenantEntities);
    }

    /**
    * @Author GroundDemo
    * @Description 根据租户ID查询租户信息
    * @Date 19:47 2024/5/31
    * @Param [tenantDto]
    * @return com.ywu.common.result.CommonResult<com.ywu.tenant.standard.entity.TenantEntity>
    **/
    public CommonResult<TenantEntity> queryTenantInfoByTenantId(TenantDto tenantDto) {
        TenantEntity tenantEntity = tenantRepository.queryTenantInfoByTenantId(tenantDto.getTenantId());
        return CommonResult.success(tenantEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 根据用户ID删除租户授权信息
    * @Date 19:32 2025/3/26
    * @Param [tenantUserDTO]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> deleteTenantPermission(TenantUserDTO tenantUserDTO) {
        // 根据用户ID删除数据表中的数据
        tenantRepository.deleteTenantUserPermissionByUserId(tenantUserDTO);
        return CommonResult.success(null);
    }
}
